package com.example.seckilldemo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
//import com.example.seckilldemo.exception.GlobalException;
import com.example.seckilldemo.exception.GlobalException;
import com.example.seckilldemo.mapper.UserMapper;
import com.example.seckilldemo.pojo.User;
import com.example.seckilldemo.service.IUserService;
//import com.example.seckilldemo.utils.CookieUtil;
import com.example.seckilldemo.utils.CookieUtil;
import com.example.seckilldemo.utils.MD5Util;
//import com.example.seckilldemo.utils.UUIDUtil;
import com.example.seckilldemo.utils.UUIDUtil;
import com.example.seckilldemo.vo.LoginVo;
import com.example.seckilldemo.vo.RespBean;
import com.example.seckilldemo.vo.RespBeanEnum;
//import io.netty.util.internal.StringUtil;
//import jakarta.annotation.Resource;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.example.seckilldemo.utils.ValidatorUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.thymeleaf.util.StringUtils;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
//    @Resource
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response){
//    public RespBean doLogin(LoginVo loginVo){
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();
//        // 后端判断数据是否为空
//        if(StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)){
//            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
//        }
//        // 判断手机号码格式是否正确
//        if(!ValidatorUtil.isMobile(mobile)){
//            return RespBean.error(RespBeanEnum.MOBILE_ERROR);
//        }
        // 根据手机号获取用户 (返回的是User pojo对象，即一个数据表对应的一个类实现，包含setter和getter方法)
//        Long mobileNum = Long.parseLong(mobile);
        User user = userMapper.selectById(mobile);
        // 判断用户信息是否输入为空
        if(user == null){
//            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
        // 判断密码是否正确
        if(!MD5Util.fromPassToDBPass(password,user.getSlat()).equals(user.getPassword())){
//            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
//        System.out.println(RespBean.success());
//        return RespBean.success();
        // 生成cookie
        String ticket = UUIDUtil.uuid();
        // 向Redis写入键值对数据（user:cookie, user class）
        redisTemplate.opsForValue().set("user:"+ticket, user);
        request.getSession().setAttribute(ticket, user);
        // 向相应的response响应体中写入cookie
        CookieUtil.setCookie(request, response, "userTicket", ticket);

        return RespBean.success(ticket);
    }

    /**
     * @description: 根据 cookie 获取用户
     *
     * @param:
     * @return:
     */

    @Override
    public User getUserByCookie(String userTicket, HttpServletRequest request, HttpServletResponse response) {
        // 如果request请求体中没有相应的cookie，则返回null
        if(StringUtils.isEmpty(userTicket)){
            return null;
        }
        User user = (User) redisTemplate.opsForValue().get("user:"+userTicket);
        // 如果cookie为空，则 set
        if(user == null){
            CookieUtil.setCookie(request, response, "userTicker", userTicket);
        }
        // 返回 Redis 中 key=user:cookie 相应的value=user
        return user;
    }

    /**
     * @description: 用户更新密码
     *
     * @param:
     * @return:
     */
    @Override
    public RespBean updatePassword(String userTicket, String password, HttpServletRequest request, HttpServletResponse response) {
        User user = getUserByCookie(userTicket, request, response);
        if(user == null){
            throw new GlobalException(RespBeanEnum.MOBLIE_NOT_EXIST);
        }
        user.setPassword(MD5Util.inputPassToDBPass(password, user.getSlat()));
        int res = userMapper.updateById(user);
        if(res == 1){
            redisTemplate.delete("user:" + userTicket);
            return RespBean.success();
        }

        return RespBean.error(RespBeanEnum.PASSWORD_UPDATE_FAIL);
    }


}
